package com.efrei.uchat.server.strategies;

import java.util.ArrayList;
import java.util.List;

import com.efrei.uchat.exception.UChatException;
import com.efrei.uchat.io.Session;
import com.efrei.uchat.message.CroomUsersMessage;
import com.efrei.uchat.message.Message;
import com.efrei.uchat.model.croom.Croom;
import com.efrei.uchat.server.UChatServer;

public class CroomUsersWorker implements MessageStrategy {

	@Override
	public List<Message> manage(Message message, UChatServer context)
			throws UChatException {
		CroomUsersMessage ret = (CroomUsersMessage) message;
		
		// lock sessions
		try {
			context.getSessionsLock().lock();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// lock crooms
		try {
			context.getCroomsLock().lock();
		} catch (InterruptedException e) {
			e.printStackTrace();
			throw new UChatException("error while blocking crooms lock");
		}
		
		try {
			Croom croom = context.getCrooms().getCroom(ret.getCroom());
			if(croom!=null) {
				// get croom's registered sessions
				for (Session session : croom.getSessions()) {
					ret.addSession(session);
				}
			}
		} finally {
			context.getCroomsLock().unlock();
			context.getSessionsLock().unlock();
		}
		
		List<Message> lst = new ArrayList<Message>();
		lst.add(ret);
		return lst;
	}

}
